package com.ruoyi.web.controller.system;

import java.util.Arrays;

public class LeastSquaresFit {
    public static void main(String[] args) {
        double[] xValues = {1, 2, 3, 4, 5};
        double[] yValues = {2, 3, 5, 7, 11};

        double[] result = calculateLeastSquares(xValues, yValues);
        double a = result[0];
        double b = result[1];

        System.out.println("y = " + a + " + " + b + "n");
    }

    public static double[] calculateLeastSquares(double[] xValues, double[] yValues) {
        int n = xValues.length;

        double sumX = 0.0;
        double sumY = 0.0;
        double sumX2 = 0.0;
        double sumXY = 0.0;

        for (int i = 0; i < n; i++) {
            sumX += xValues[i];
            sumY += yValues[i];
            sumX2 += xValues[i] * xValues[i];
            sumXY += xValues[i] * yValues[i];
        }

        double delta = sumX * sumX - n * sumX2;
        double a = (n * sumXY - sumX * sumY) / delta;
        double b = (sumY * sumX2 - sumX * sumXY) / delta;

        return new double[]{a, b};
    }
}